package cn.bytecollege.admin.dao;

import cn.bytecollege.common.dao.BaseDao;
import cn.bytecollege.common.entity.Orders;

import java.sql.SQLException;
import java.util.List;

/**
 * @author NJK
 */
public class OrderDao extends BaseDao<Orders,Integer> {
    /**
     * 根据支付状态分页查询订单
     * @author NJK
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public List<Orders> findOrderByPage(int pageIndex, int pageSize, int payflag){
        String sql = "SELECT order_id,order_number,create_time,total_price,pay_flag " +
                "FROM orders " +
                "Where pay_flag=? " +
                "limit ?,?";
        Object[] objects = {payflag,(pageIndex-1)*pageSize,pageSize};
        return helper.executeQuery(sql, Orders.class,objects);
    }
    /**
     * 根据支付状态计算总条数
     * @author NJK
     * @return
     */
    public int countByPayFlag(int payflag){
        String sql = "SELECT COUNT(*) FROM orders WHERE pay_flag = ?";
        return helper.executeScale(sql,payflag);
    }

    /**
     * 统计所有的订单数量
     * @author NJK
     * @return
     */
    public int count(){
        String sql = "SELECT COUNT(*) FROM orders";
        return helper.executeScale(sql);
    }
    /**
     * 修改订单的支付状态
     * @author NJK
     * @param orders
     * @return
     */
    public int updatePayFlag(Orders orders) {
        String sql = "UPDATE orders SET pay_flag = 1 WHERE order_id = ?";
        Object[] objects = {orders.getOrderId()};
        return helper.executeUpdate(sql,objects);
    }

    /**
     * 根据订单号删除订单
     * @author NJK
     * @param orderNumber
     * @return
     */
    public int deleteByOrderNumber(String orderNumber) {
        String sql = "DELETE orders,order_detail " +
                "from orders left join order_detail " +
                "on orders.order_number =order_detail.order_number " +
                "where orders.order_number=?";
        return helper.executeUpdate(sql,orderNumber);
    }

    /**
     * 在订单表中添加数据
     * @author zhy
     * @param orders
     * @return
     */
    @Override
    public int save(Orders orders) {
        String sql = "INSERT INTO ORDERS (ORDER_NUMBER,PAY_FLAG,TOTAL_PRICE,CREATE_TIME) VALUES(?,0,?,?)";
        Object[] objects = {orders.getOrderNumber(),orders.getTotalPrice(),orders.getCreateTime()};
        return helper.executeUpdate(sql,objects);

    }

    public void begin() throws SQLException {
        helper.begin();
    }
    public void commit() throws SQLException {
        helper.commit();
    }
    public void rollback() throws SQLException {
        helper.rollback();
    }
    public void close() throws SQLException {
        helper.close();
    }
}
